package com.gitee.wsl.ext.number

import kotlin.jvm.JvmName
import kotlin.math.max
import kotlin.math.min

fun saturate(x: Double) = max(0.0, min(1.0, x))

fun linearstep(edge0: Double, edge1: Double, x: Double): Double = saturate((x - edge0) / (edge1 - edge0))

/**
 * Smoothstep
 * @param edge0
 * @param edge1
 * @param x
 * @return a mapped value in the interval [0, 1]
 */
fun smoothstep(edge0: Double, edge1: Double, x: Double): Double {
    // Scale, bias and saturate x to 0..1 range
    val u = saturate((x - edge0) / (edge1 - edge0))
    // Evaluate polynomial
    return u * u * (3 - 2 * u)
}


@JvmName("doubleSmoothstep")
fun Double.smoothstep(edge0: Double, edge1: Double) = smoothstep(edge0, edge1, this)

/**
 * Smoothstep
 * @param edge0
 * @param edge1
 * @param x
 * @return a mapped value in the interval [0, 1]
 */
fun smoothstepIn(edge0: Double, edge1: Double, x: Double): Double {
    // Scale, bias and saturate x to 0..1 range
    val u = saturate((x - edge0) / (edge1 - edge0))
    // Evaluate polynomial

    return if (x < 0.5)
        u * u * (3 - 2 * u)
    else {
        u
    }
}